/*
 * author:gxy
 * 验证工具类
 * createTime:2021-07-10 13:12
 * updateTime:2021-07-10 13:28
 */

package com.yjetms.ulits;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Validation {

    //电话
    private static final Pattern PHONE_NUM = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");

    //身份证
    public static final Pattern IDCARD = Pattern.compile("(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
            "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)");

    //邮箱
    public static final Pattern EMAIL = Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?");

    /**
     * 判断是否为电话号码 符合返回ture
     * @param str 电话号码
     * @return Boolean 是否符合
     */
    public static Boolean isPhone(String str){
        return Regular(str,PHONE_NUM);

    }

    /**
     * 判断身份照号码是否正确 符合返回ture
     * @param str 身份照号码
     * @return Boolean 是否符合
     */
    public static Boolean isIDCard(String str){
        boolean matches = Regular(str,IDCARD);
        if (matches) {
            if (str.length() == 18) {
                try {
                    char[] charArray = str.toCharArray();
                    //前十七位加权因子
                    int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
                    //这是除以11后，可能产生的11位余数对应的验证码
                    String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
                    int sum = 0;
                    for (int i = 0; i < idCardWi.length; i++) {
                        int current = Integer.parseInt(String.valueOf(charArray[i]));
                        int count = current * idCardWi[i];
                        sum += count;
                    }
                    char idCardLast = charArray[17];
                    int idCardMod = sum % 11;
                    return idCardY[idCardMod].equalsIgnoreCase(String.valueOf(idCardLast));
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

        }
        return matches;
    }

    /**
     * 判断邮箱是否正确 符合返回ture
     * @param str 邮箱
     * @return Boolean 是否符合
     */
    public static boolean isEmail(String str){
        return Regular(str,EMAIL);
    }

    /**
     * 匹配是否符合正则表达式pattern 匹配返回true
     * @param str 匹配的字符串
     * @param pattern 匹配模式
     * @return boolean
     */
    private static  boolean Regular(String str,Pattern pattern){
        if(null == str || str.trim().length()<=0)
            return false;
        Matcher m = pattern.matcher(str);
        return m.matches();
    }

}
